import {
  DashboardOutlined,
  SettingOutlined,
  UserOutlined,
} from "@ant-design/icons";
import { IAuthLoader } from "@lgq/routes/AuthLoader";
import { usePathStore, useStore } from "@lgq/store";
import { IMenu } from "@lgq/types";
import { Menu, MenuProps } from "antd";
import { useEffect, useState } from "react";
import { useLocation, useNavigate, useRouteLoaderData } from "react-router-dom";

type MenuItem = Required<MenuProps>["items"][number];

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[]
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
  } as MenuItem;
}

const items: MenuItem[] = [
  getItem("Dashboard", "/dashboard", <DashboardOutlined />, [
    getItem("工作台", "/dashboard/workbench"),
    getItem("分析", "/dashboard/analysis"),
  ]),
  getItem("系统管理", "/system", <SettingOutlined />, [
    getItem("用户管理", "/system/user"),
    getItem("角色管理", "/system/role"),
    getItem("菜单管理", "system/menu"),
  ]),
  getItem("个人中心", "/personal", <UserOutlined />, [
    getItem("个人信息", "info"),
    getItem("个人设置", "setting"),
  ]),
];

const getIcon = (menuCode: string) => {
  if (menuCode === "dashboard") {
    return <DashboardOutlined />;
  }
  if (menuCode === "system") {
    return <SettingOutlined />;
  }
  if (menuCode === "personal") {
    return <UserOutlined />;
  }
  return "";
};

const SiderMenu = () => {
  const navigator = useNavigate();
  const { pathname } = useLocation();

  const data = useRouteLoaderData("layout") as IAuthLoader;
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [openKeys, setOpenKeys] = useState<string[]>([]);
  const [menuList, setMenuList] = useState<MenuItem[]>([]);

  ///菜单转换
  const switchTreeMenu = (
    menuList: IMenu.MenuItem[],
    treeList: IMenu.MenuItem[] = []
  ) => {
    menuList.forEach((item, index) => {
      if (item.menuType === 1 && item.menuState === 1) {
        if (!item?.children?.length) {
          return treeList.push(item);
        } else {
          item.path =
            item.path?.indexOf("/") === 0 ? item.path : "/" + item.path;
          item.children.forEach((childrenItem, index) => {
            childrenItem.path = item.path + "/" + childrenItem.path;
          });
          item.children = switchTreeMenu(item.children);
          treeList.push(item);
        }
      }
    });
    return treeList;
  };

  // 递归生成菜单
  const getTreeMenu = (
    menuList: IMenu.MenuItem[],
    treeList: MenuItem[] = []
  ) => {
    menuList.forEach((item, index) => {
      if (item.menuType === 1 && item.menuState === 1) {
        if (!item?.children?.length)
          return treeList.push(
            getItem(
              item.menuName,
              item.path || "",
              getIcon(item.menuCode ?? "")
            )
          );
        treeList.push(
          getItem(
            item.menuName,
            item.path || "",
            getIcon(item.menuCode ?? ""),
            getTreeMenu(item.children || [])
          )
        );
      } else {
      }
    });
    return treeList;
  };

  const { updateMenuItems } = useStore();

  useEffect(() => {
    console.log("menu");
    const switchList = switchTreeMenu(data.menuList);
    console.log(switchList);
    const menuList = getTreeMenu(switchList);
    console.log(menuList);
    setMenuList(menuList);
    updateMenuItems(switchList);

  usePathStore.subscribe((state, preState) => {
    console.log("11111")
    console.log(state.path);
     console.log(preState.path);
    if (state.path) {
      const paths = state.path.replace("/", "").split("/");
      if (paths.length > 1) {
        const key = "/" + paths[0] + "/" + paths[1];
        setSelectedKeys([key]);
      } else {
        setSelectedKeys([state.path]);
      }
      const openkey ="/" +  state.path.replace("/", "").split("/")[0];
      setOpenKeys([openkey]);
    }
  });
  }, []);



  const onMenuItemSelect = (item: any) => {
    setSelectedKeys(item.selectedKeys);
    navigator(item.key);
  };

  const onOpenChange = (openKeys: string[]) => {
    setOpenKeys(openKeys);
  };

  return (
    <div>
      <Menu
        theme="dark"
        style={{ height: "100%" }}
        selectedKeys={selectedKeys}
        openKeys={openKeys}
        mode="inline"
        items={menuList}
        onClick={onMenuItemSelect}
        onOpenChange={onOpenChange}
      />
    </div>
  );
};

export default SiderMenu;
